package org.jeecg.lawcase.data.reader.impl;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.lawcase.data.reader.DataImportApadter;
import org.jeecg.lawcase.data.reader.DataImportManager;
import org.jeecg.lawcase.data.reader.DataTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Component
public class CSVDataImportImpl implements DataImportApadter {

    public CSVDataImportImpl() {
        DataImportManager.registerService(this.getFileType(), this);
    }

    @Override
    public String getFileType() {
        return "csv";
    }

    @Override
    public DataTemplate importData(String fileName, InputStream inputStream) throws JeecgBootException {
        String line = null;
        DataTemplate dataTemplate = new DataTemplate();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
            while (StringUtils.isNotBlank(line = br.readLine())) {
                // 按行读取数据
                if(line == null){
                   this.setHeader(dataTemplate, line);
                } else {
                    this.addRow(dataTemplate, line);
                }
            }
        } catch (Exception e){
            throw new JeecgBootException(e);
        }
        return dataTemplate;
    }

    /**
     * 读取文件头
     * @param dataTemplate
     * @param line
     */
    private void setHeader(DataTemplate dataTemplate, String line){
        String[] titles = line.split(",");
        for(String title: titles){
            dataTemplate.getHeaders().add(title);
        }
    }

    /**
     * 读取数据内容
     * @param dataTemplate
     * @param line
     */
    private void addRow(DataTemplate dataTemplate, String line){
        String[] datas = line.split(",");
        List<String> row = new ArrayList<>();
        for(String data: datas){
            row.add(data);
        }
        dataTemplate.getDatas().add(row);
    }
}
